package com.sd.repay.auth.channel;

import com.alibaba.fastjson.JSONObject;
import com.sd.repay.auth.RealAuthChannelCache;
import com.sd.repay.pojo.RealAuthChannel;
import com.sd.repay.pojo.RealAuthRecord;
import com.sd.repay.sms.HttpUtil;
import com.sd.repay.utils.Md5Util;
import com.sd.repay.utils.ParamUtil;
import com.sd.repay.utils.WebUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * 松鸿
 * <p>
 * <p>
 * 通道支持三要素及四要素认证
 *
 * @author
 */
@Service
public class SHRealService extends BaseRealAuth {

    private Logger log = LoggerFactory.getLogger(SHRealService.class);

    private final String authChannel = "SH_REAL";

    private final String channelName = "洪松";

    @Override
    public void twoElementsCheck(RealAuthRecord authRecord) {
        log.info(channelName.concat("二要素认证[{}]执行开始"), authRecord.toJson());
        authRecord.setAuthStatus("2");
        authRecord.setRespMsg("渠道未开通此业务");
    }


    @Override
    public void threeElementsCheck(RealAuthRecord authRecord) {
        log.info(channelName.concat("三要素认证[{}]执行开始"), authRecord.toJson());
        String status = "";
        String resultCode = "";
        String resultMsg = "";
        String orderNo = authRecord.getRecordNo();
        try {
            RealAuthChannel channel = (RealAuthChannel) RealAuthChannelCache.getChannel(authChannel);
            String url = channel.getRealAuthUrl().concat("check3.do");
            String key = channel.getSignKey();
            String appId = channel.getChannelAccNo();
            String version = channel.getChannelVersion();
            String accNo = authRecord.getAccountNo();
            String realName = authRecord.getReanName();
            String idcard = authRecord.getIdCardNo();

            Map<String, String> date = new TreeMap<>();
            date.put("bizNo", orderNo);
            date.put("cardNo", accNo);
            date.put("idNo", idcard);
            date.put("realName", realName);
            String sendStr = pubParanm(date, key, appId, version);

            Map<String, String> header = new HashMap<String, String>();
            header.put("Accept", "application/json;charset=" + WebUtil.utf8Encode);
            HttpUtil httpUtil = new HttpUtil(timeOut, timeOut, WebUtil.utf8Encode);
            String resultStr = httpUtil.httpStream(url, sendStr, header, WebUtil.utf8Encode);
            log.info(channelName.concat("三要素认证提交[{}], 渠道响应[{}]"), sendStr, resultStr);

            if (StringUtils.isBlank(resultStr)) {
                status = "2";
                resultCode = "response is null";
                resultMsg = "*渠道未响应";
            } else {

                JSONObject resultJson = null;
                try {
                    resultJson = JSONObject.parseObject(resultStr);
                } catch (Exception e) {
                    log.error(channelName.concat("三要素认证[{}]渠道响应错误的JSON报文格式[{}]"), authRecord.toJson(), resultStr);
                    status = "2";
                    resultCode = "real error";
                    resultMsg = "*认证出现错误,渠道响应报文格式异常";
                }

                if (resultJson != null) {
                    String code = StringUtils.defaultString(resultJson.getString("rspCd"));
                    String msg = StringUtils.defaultString(resultJson.getString("rspInf"));

                    if ("00000".equals(code)) {
                        String resultData = StringUtils.defaultString(resultJson.getString("data"));
                        JSONObject dateJson = JSONObject.parseObject(resultData);
                        String checkCode = StringUtils.defaultString(dateJson.getString("code"));
                        String checkMsg = StringUtils.defaultString(dateJson.getString("msg"));
                        if ("00".equals(checkCode)) {
                            status = "1";
                        } else {
                            status = "2";
                        }

                        resultCode = checkCode;
                        resultMsg = checkMsg;

                    } else {
                        status = "2";
                        resultCode = code;
                        resultMsg = msg;
                    }

                }
            }
        } catch (Exception e) {
            log.error(channelName.concat("三要素认证出现异常，请求[{}]出现异常：{}"), authRecord.toJson(), e.getMessage());
            status = "2";
            resultCode = "real error";
            resultMsg = "*认证出现错误,系统异常";
        }

        authRecord.setAuthStatus(status);
        authRecord.setRespCode(resultCode);
        authRecord.setRespMsg(resultMsg);
        authRecord.setAuthChannel(authChannel);
        log.info(channelName.concat("三要素认证执行结束,订单号[{}]，认证状态[{}]，渠道响应[{}]，响应描述[{}]"), new Object[]{orderNo, status, resultCode, resultMsg});
    }

    @Override
    public void fourElementsCheck(RealAuthRecord authRecord) {
        log.info(channelName.concat("四要素认证[{}]执行开始"), authRecord.toJson());
        String status = "";
        String resultCode = "";
        String resultMsg = "";
        String orderNo = authRecord.getRecordNo();
        try {
            RealAuthChannel channel = (RealAuthChannel) RealAuthChannelCache.getChannel(authChannel);
            String url = channel.getRealAuthUrl().concat("check4.do");
            String key = channel.getSignKey();
            String appId = channel.getChannelAccNo();
            String version = channel.getChannelVersion();
            String accNo = authRecord.getAccountNo();
            String realName = authRecord.getReanName();
            String idcard = authRecord.getIdCardNo();
            String phoneNo = authRecord.getMobileNo();

            Map<String, String> date = new TreeMap<>();
            date.put("bizNo", orderNo);
            date.put("cardNo", accNo);
            date.put("idNo", idcard);
            date.put("realName", realName);
            date.put("phoneNo", phoneNo);
            String sendStr = pubParanm(date, key, appId, version);

            Map<String, String> header = new HashMap<String, String>();
            header.put("Accept", "application/json;charset=" + WebUtil.utf8Encode);
            HttpUtil httpUtil = new HttpUtil(timeOut, timeOut, WebUtil.utf8Encode);
            String resultStr = httpUtil.httpStream(url, sendStr, header, WebUtil.utf8Encode);
            log.info(channelName.concat("四要素认证提交[{}], 渠道响应[{}]"), sendStr, resultStr);

            if (StringUtils.isBlank(resultStr)) {
                status = "2";
                resultCode = "response is null";
                resultMsg = "*渠道未响应";
            } else {

                JSONObject resultJson = null;
                try {
                    resultJson = JSONObject.parseObject(resultStr);
                } catch (Exception e) {
                    log.error(channelName.concat("四要素认证[{}]渠道响应错误的JSON报文格式[{}]"), authRecord.toJson(), resultStr);
                    status = "2";
                    resultCode = "real error";
                    resultMsg = "*认证出现错误,渠道响应报文格式异常";
                }

                if (resultJson != null) {
                    String code = StringUtils.defaultString(resultJson.getString("rspCd"));
                    String msg = StringUtils.defaultString(resultJson.getString("rspInf"));

                    if ("00000".equals(code)) {
                        String resultData = StringUtils.defaultString(resultJson.getString("data"));
                        JSONObject dateJson = JSONObject.parseObject(resultData);
                        String checkCode = StringUtils.defaultString(dateJson.getString("code"));
                        String checkMsg = StringUtils.defaultString(dateJson.getString("msg"));
                        if ("00".equals(checkCode)) {
                            status = "1";
                        } else {
                            status = "2";
                        }

                        resultCode = checkCode;
                        resultMsg = checkMsg;

                    } else {
                        status = "2";
                        resultCode = code;
                        resultMsg = msg;
                    }

                }
            }
        } catch (Exception e) {
            log.error(channelName.concat("四要素认证出现异常，请求[{}]出现异常：{}"), authRecord.toJson(), e.getMessage());
            status = "2";
            resultCode = "real error";
            resultMsg = "*认证出现错误,系统异常";
        }

        authRecord.setAuthStatus(status);
        authRecord.setRespCode(resultCode);
        authRecord.setRespMsg(resultMsg);
        authRecord.setAuthChannel(authChannel);
        log.info(channelName.concat("四要素认证执行结束,订单号[{}]，认证状态[{}]，渠道响应[{}]，响应描述[{}]"), new Object[]{orderNo, status, resultCode, resultMsg});
    }


    /**
     * 组织请求报文
     *
     * @param date    业务参数
     * @param key     签名密钥
     * @param appId   账户编号
     * @param version 版本编号
     * @return String 请求原文
     */
    private String pubParanm(Map<String, String> date, String key, String appId, String version) {
        JSONObject sendMap = new JSONObject();
        sendMap.put("appId", appId);
        sendMap.put("v", version);

        String signTemp = ParamUtil.getOrderedParas(date);
        String sign = Md5Util.MD5Encode(signTemp.concat("&key=").concat(key), WebUtil.utf8Encode, true);

        sendMap.put("sign", sign);
        sendMap.put("data", date);

        return sendMap.toString();
    }

}
